package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.mapper.EmployeeMapper;
import com.itheima.reggie.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

/**
 * @author Lff
 * @date 2022/2/25
 * Employee的业务层
 */
@Service
@Slf4j
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee>
        implements EmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public Employee login(Employee employee) {
        LambdaQueryWrapper<Employee> qw = Wrappers.lambdaQuery(Employee.class);
        qw.eq(Employee::getUsername, employee.getUsername());
        Employee login = employeeMapper.selectOne(qw);
        return login;
    }

    @Override
    public Page<Employee> getAllByPage(Integer page, Integer pageSize, String name) {
        Page<Employee> pages = new Page<>(page, pageSize);
        LambdaQueryWrapper<Employee> qw = Wrappers.lambdaQuery(Employee.class);
        qw.like(StringUtils.isNotEmpty(name), Employee::getName, name);
        employeeMapper.selectPage(pages, qw);
        return pages;
    }


    @Override
    public boolean addEmp(Employee employee) {
        //填充密码
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        //默认状态是可用
        employee.setStatus(1);
        int result = employeeMapper.insert(employee);
        return result == 1;
    }

    @Override
    public boolean updateEmp(Employee employee) {
        LambdaUpdateWrapper<Employee> uw = new LambdaUpdateWrapper<>();
        log.info("emp  => {}", employee.toString());
        int result = employeeMapper.updateById(employee);
        return result == 1;
    }
}
